﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;

using CE.Mail;
using CE.Image;
using CE.User;
using CE.Database;
using CE.HomeLoan;
using CE.Global;
using CE.Provider;

public partial class home_loan_results : System.Web.UI.Page
{
    int _curPackageNo = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session[CE.Global.General.HLId] == null)
        {
            Response.Redirect("home-loan.aspx");
        }

        if (!IsPostBack)
        {

            if (Request.IsSecureConnection)
            {
                string redirectUrl = Request.Url.ToString().Replace("https:", "http:");
                Response.Redirect(redirectUrl);
            }


            Cache.Remove("HLResult");
            ShowSummaryDetails();
            ResultsQuotesDataBind();
            Session[CE.Global.General.HLResultId] = null;
            LogUserViewedHistory();
            //LoadValues();


            if (Session[General.UserId] != null)
            {
                if (Session[General.UserName] != null)
                {
                    if (Session[General.UserName].ToString() != "")
                    {
                        txtFullName.Text = Session[General.UserName].ToString();
                        txtMobileNo.PhoneNo = Session[General.UserPhoneNo].ToString();
                        txtEmail.Text = Session[General.UserEmail].ToString();

                        txtFullName.ReadOnly = true;
                        txtMobileNo.IsReadOnly = true;
                        txtEmail.ReadOnly = true;
                    }
                }
                else if (Session[General.HLUserName] != null)
                {
                    if (Session[General.HLUserName].ToString() != "")
                    {
                        txtFullName.Text = Session[General.HLUserName].ToString();
                        txtMobileNo.PhoneNo = Session[General.HLPhoneNo].ToString();
                        txtEmail.Text = Session[General.HLEmail].ToString();

                        txtFullName.ReadOnly = true;
                        txtMobileNo.IsReadOnly = true;
                        txtEmail.ReadOnly = true;
                    }
                }
            }
            else
            {
                txtFullName.ReadOnly = false;
                txtMobileNo.IsReadOnly = false;
                txtEmail.ReadOnly = false;
            }


            //Enable FullName, Mobile No, Email for provider to change
            if (Session[General.UserId] != null &&
            Session[CE.Global.General.ProviderCompanyId] != null &&
            Session[CE.Global.General.UserTypeId] != null)
            {
                if (Convert.ToInt32(Session[CE.Global.General.UserTypeId]) ==
                    Convert.ToInt32(CE.Global.CEUserType.Provider))
                {
                    txtFullName.Text = "";
                    txtMobileNo.PhoneNo = "";
                    txtEmail.Text = "";

                    txtFullName.ReadOnly = false;
                    txtMobileNo.IsReadOnly = false;
                    txtEmail.ReadOnly = false;
                }
            }

        }
    }

    private void ShowSummaryDetails()
    {
        HomeLoan _homeloan = new HomeLoan();
        HomeLoanDB _homeloandb = new HomeLoanDB();
        _homeloan = _homeloandb.GetHomeLoan(Convert.ToInt64(Session[General.HLId].ToString()));
        if (_homeloan != null)
        {
            if (_homeloan.HLMortgageType == 1)
            {
                lblMortageType.Text = "Refinancing";
            }
            else
            {
                lblMortageType.Text = "New Loan";
            }

            if (_homeloan.HLPropertyType == 1)
            {
                lblPropertyType.Text = "HDB";
            }
            else
            {
                lblPropertyType.Text = "Private";
            }

            //if (_homeloan.HLProperty == 1)
            //{
            //    lblPropertyType.Text += " (Completed)";
            //}
            //else
            //{
            //    lblPropertyType.Text += " (UnCompleted)";
            //}

            lblLoanAmount.Text = "S$ " + _homeloan.HLAmount.ToString("#,000") + " (" + _homeloan.HLLoanTenure.ToString() + " years) ";
            //if (_homeloan.HLLockIn)
            //{
            //    lblLockIn.Text = "Yes";
            //}
            //else
            //{
            //    lblLockIn.Text = "No";
            //}

            //if (_homeloan.HLInterestRate == 1)
            //{
            //    lblInterestType.Text = "Fixed";
            //}
            //else
            //{
            //    lblInterestType.Text = "Floating";
            //}
        }
    }
    private void LogUserViewedHistory()
    {
        UserViewHistoryDB _userviewdb = new UserViewHistoryDB();
        _userviewdb.LogViewedHistory("HL", Request, "Home loans results.");
    }

    private void ResultsQuotesDataBind()
    {
        GetTempResultTableTwo();
        gvHLResults.DataSource = null;
        DataView dv = new DataView((DataTable)Cache["HLResult"]);
        //dv.RowFilter = "ProductName";
        if (dv.Count > 0)
        {
            //dv.Sort = "CXPackageName ASC";
            gvHLResults.DataSource = dv;
        }
        gvHLResults.DataBind();
    }


    private void CalculateInstallment()
    {
        MyDatabase _db = new MyDatabase();

        DataTable _dtResult = new DataTable();
        string _spName = "sproceHomeLoanCalculationForThreeYears";
        SortedList _sPara = new SortedList();

        Int64 _HLId = Convert.ToInt64(Session[CE.Global.General.HLId].ToString());
        _sPara.Add("@HLId", _HLId);

        if (Session[General.UserId] != null)
        {
            _sPara.Add("@RefCEUserID", Session[General.UserId].ToString());
        }
        else
        {
            _sPara.Add("@RefCEUserID", 0);
        }

        if (Session[General.UserId] != null &&
            Session[CE.Global.General.ProviderCompanyId] != null &&
            Session[CE.Global.General.UserTypeId] != null)
        {
            if (Convert.ToInt32(Session[CE.Global.General.UserTypeId]) ==
                Convert.ToInt32(CE.Global.CEUserType.Provider))
            {
                _sPara.Add("@ProviderCompanyID", Session[CE.Global.General.ProviderCompanyId].ToString());
            }
            else
            {
                _sPara.Add("@ProviderCompanyID", 0);
            }
        }
        else
        {
            _sPara.Add("@ProviderCompanyID", 0);
        }

        _db.ExecuteNonSqlSP(_spName, _sPara);
    }

    private void GetTempResultTableTwo()
    {
        CalculateInstallment();

        MyDatabase _db = new MyDatabase();
        DataTable _dtResult = new DataTable();
        string _spName = "sprocHLRequestSelectResultItemList";
        //if (Session[General.Guest] != null)
        //{
        //    if (Session[General.Guest].ToString() == "Provider")
        //    {
        //        if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("MayBankProviderCompanyId"))
        //            _spName = "sprocHLRequestSelectResultItemList_MayBank";
        //    }
        //    else
        //    {
        //        _spName = "[sprocHLRequestSelectResultItemList]";
        //    }
        //}
        //else
        //{
        //    _spName = "[sprocHLRequestSelectResultItemList]";
        //}
        SortedList _sPara = new SortedList();
        Int64 _HLId = Convert.ToInt64(Session[CE.Global.General.HLId].ToString());
        _sPara.Add("@HLId", _HLId);
        if (Session[General.UserId] != null)
        {
            _sPara.Add("@RefCEUserID", Session[General.UserId].ToString());
        }
        else
        {
            _sPara.Add("@RefCEUserID", 0);
        }

        _dtResult = _db.GetDataTableBySP(_spName, _sPara);
        Cache["HLResult"] = _dtResult;
    }

    protected void gvHLResults_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            _curPackageNo++;
            Label lblTempId = (Label)e.Row.FindControl("lblTempId");
            lblTempId.Text = DataBinder.Eval(e.Row.DataItem, "HLTempID").ToString();

            //Label lblPackageName = (Label)e.Row.FindControl("lblPackageName");
            //lblPackageName.Text = DataBinder.Eval(e.Row.DataItem, "CXPackageName").ToString();

            Label lblPackageName = (Label)e.Row.FindControl("lblPackageNo");
            lblPackageName.Text = _curPackageNo.ToString();

            Label lblTotalInterest = (Label)e.Row.FindControl("lblTotalInterest");
            lblTotalInterest.Text = "S$ " + FormatThousandSeperator(DataBinder.Eval(e.Row.DataItem, "ThreeYearInterest").ToString());

            Label lblYear1MonthlyPayment = (Label)e.Row.FindControl("lblYear1MonthlyPayment");
            lblYear1MonthlyPayment.Text = "S$ " + FormatThousandSeperator(DataBinder.Eval(e.Row.DataItem, "Y1Installment").ToString());

            Label lblYear2MonthlyPayment = (Label)e.Row.FindControl("lblYear2MonthlyPayment");
            lblYear2MonthlyPayment.Text = "S$ " + FormatThousandSeperator(DataBinder.Eval(e.Row.DataItem, "Y2Installment").ToString());

            Label lblYear3MonthlyPayment = (Label)e.Row.FindControl("lblYear3MonthlyPayment");
            lblYear3MonthlyPayment.Text = "S$ " + FormatThousandSeperator(DataBinder.Eval(e.Row.DataItem, "Y3Installment").ToString());

            Label lblYear4MonthlyPayment = (Label)e.Row.FindControl("lblYear4MonthlyPayment");
            lblYear4MonthlyPayment.Text = "<strong>S$ " + FormatThousandSeperator(DataBinder.Eval(e.Row.DataItem, "Y4Installment").ToString()) + "</strong>";

            Label lblLockInPeriod = (Label)e.Row.FindControl("lblLockInPeriod");
            Image imgLockIn = (Image)e.Row.FindControl("imgLockInStatus");
            int _lockInYear = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "LockInPeriod").ToString());
            bool _IsLockIn = Convert.ToBoolean(DataBinder.Eval(e.Row.DataItem, "IsLockIn").ToString());

            if (_lockInYear == 0)
            {
                lblLockInPeriod.Text = "No Lock-In";
                lblLockInPeriod.Attributes.Add("style", "display:none;");
            }
            else if (_lockInYear == 1)
            {
                lblLockInPeriod.Text = "<br/>1 year";
            }
            else if (_lockInYear > 1)
            {
                lblLockInPeriod.Text = "<br/>" + _lockInYear.ToString() + " years";
            }

            if (_IsLockIn)
            {
                imgLockIn.ImageUrl = "~/images/icon/tick.png";
            }
            else
            {
                imgLockIn.ImageUrl = "~/images/icon/x.png";
                lblLockInPeriod.Text = "No Lock-In";
                lblLockInPeriod.Attributes.Add("style", "display:none;");
            }
        }
    }

    private string FormatThousandSeperator(string strValue)
    {
        string _retValue = strValue;
        try
        {
            Double _dValue = Convert.ToDouble(strValue);
            Double _dCValue = 1000.00d;
            if (_dValue >= _dCValue)
            {
                _retValue = _dValue.ToString("#,000.00");
            }
            else
            {
                _retValue = _dValue.ToString("#.00");
            }
        }
        catch (Exception Ex)
        {
            throw Ex;
        }


        return _retValue;
    }

    protected void ibtnBack_Click(object sender, EventArgs e)
    {
        Response.Redirect("home-loan.aspx");
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        bool isChecked;
        HyperLink _hplLink = new HyperLink();
        string _baseUrl = "http://" + Request.Url.Host.ToString();
        string[] arrSelectedItem = new string[4];
        arrSelectedItem[0] = "0";
        arrSelectedItem[1] = "0";
        arrSelectedItem[2] = "0";
        arrSelectedItem[3] = "0";


        string[] arrSelectedPackage = new string[4];
        arrSelectedPackage[0] = "";
        arrSelectedPackage[1] = "";
        arrSelectedPackage[2] = "";
        arrSelectedPackage[3] = "";

        int _curItem = 0;
        foreach (GridViewRow vRow in gvHLResults.Rows)
        {
            isChecked = ((CheckBox)vRow.FindControl("cbHLSelect")).Checked;
            if (isChecked)
            {
                arrSelectedItem[_curItem] = ((Label)vRow.FindControl("lblTempId")).Text;

                string _tmpPackageInfo = "<tr><td height=\"45\" align=\"center\" style=\"background:#d5d5d5; border-bottom:1px solid #ccc;\">" + (_curItem + 1).ToString() + "</td>";
                //string _tmpPackageInfo = "<tr>";
                _tmpPackageInfo += "<td align=\"center\" style=\"background:#bfbfbf; color:#313131;\"><strong>" + ((Label)vRow.FindControl("lblTotalInterest")).Text + "</strong></td>";
                string _strLockInStatusImageUrl = ((Image)vRow.FindControl("imgLockInStatus")).ImageUrl;
                if (_strLockInStatusImageUrl.Contains("tick.png"))
                {
                    _strLockInStatusImageUrl = _baseUrl + "/images/icon/tick_2.png";
                }
                else
                {
                    _strLockInStatusImageUrl = _baseUrl + "/images/icon/x_2.png";
                }
                _tmpPackageInfo += "<td align=\"center\" style=\"background:#bfbfbf; color:#fffff;\"><img alt=\"Lock-In Period\" src=\"" + _strLockInStatusImageUrl + "\" /><br/>" + ((Label)vRow.FindControl("lblLockInPeriod")).Text + "</td></tr>";

                arrSelectedPackage[_curItem] = _tmpPackageInfo;
                _curItem++;
                if (_curItem == 4) break;
            }
        }


        if (Session[General.HLId] != null)
        {
            HomeLoan _homeloan = new HomeLoan();
            HomeLoanDB _homeloandb = new HomeLoanDB();
            _homeloan = _homeloandb.GetHomeLoan(Convert.ToInt64(Session[General.HLId].ToString()));
            if (_homeloan != null)
            {
                _homeloan.Status = true;
                _homeloan.NInfo1 = Convert.ToInt64(arrSelectedItem[0]);
                _homeloan.NInfo2 = Convert.ToInt64(arrSelectedItem[1]);
                _homeloan.NInfo3 = Convert.ToInt64(arrSelectedItem[2]);
                _homeloan.NInfo4 = Convert.ToInt64(arrSelectedItem[3]);
                _homeloan.Email = txtEmail.Text;
                _homeloan.FullName = txtFullName.Text;
                _homeloan.ContactNo = txtMobileNo.GetPhoneNo();
            }

            Int64 _retValue = _homeloandb.Insert(_homeloan);
            if (_retValue > 0)
            {
                StringBuilder strEmailBody = new StringBuilder();
                strEmailBody.Append("<body class='email_body'>");
                strEmailBody.Append("<style type='text/css'>");
                strEmailBody.Append(".email_body {background:white;margin:0; padding:0; color:#4c4c4c; font-family:Arial, Helvetica, sans-serif; font-size:0.85em;}");
                strEmailBody.Append("a {text-decoration:underline;color:#2c95cc;} ");
                strEmailBody.Append("</style>");

                strEmailBody.Append("<center><table cellspacing='0' cellpadding='0' width='596px'><tr><td>");

                strEmailBody.Append("<tr><td><a href=\"http://www.comparexpress.com/\" target=\"_blank\"><img src=\"" + _baseUrl + "/images/email/header_homeloan.png\" width='596' height=\"187\" alt=\"CompareXpress\" border=\"0\" /></a></td></tr>");

                strEmailBody.Append("<tr><td align='center'><table width='510' border='0' cellpadding='5' cellspacing='0'><tr><td>");
                strEmailBody.Append("<strong>Dear " + txtFullName.Text + ",</strong><br/><br/>");
                strEmailBody.Append("You used CompareXpress for your Home Loans quote. <br/>Thank you very much for your interest in CompareXpress Home Loans service.<br/><br/>");
                strEmailBody.Append("</td></tr></table></td></tr>");

                strEmailBody.Append("<tr><td align='center'><table width='510' border='0' cellpadding='5' cellspacing='0'>");
                strEmailBody.Append("<tr><td width='204'>Mortgage Type</td><td width='306' align='center' style=\"background:#e5e5e5;\">" + lblMortageType.Text + "</td></tr>");
                strEmailBody.Append("<tr><td>Property Type</td><td align='center' style=\"background:#e5e5e5\">" + lblPropertyType.Text + "</td></tr>");
                strEmailBody.Append("<tr><td style=\"background:#e5e5e5;\">Loan Amount</td><td align=\"center\" style=\"background:#d5d5d5; color:#313131; font-size:14px;\"><strong>" + lblLoanAmount.Text + "</strong></td></tr></table>");

                strEmailBody.Append("<hr size='1' color='#b8b8b8' width='510'/>");
                strEmailBody.Append("<table width='510' border='0' cellpadding='5' cellspacing='2'>");
                //strEmailBody.Append("<th width='40%' height='40' align=\"center\" style=\"background:#c5c5c5;\"><strong>Package</strong></th>");
                strEmailBody.Append("<th width='10%' height='40' align=\"center\" style=\"background:#c5c5c5;\"><strong>No.</strong></th>");
                strEmailBody.Append("<th width='45%' align='center' style=\"background:#c5c5c5;\"><strong>Total Interest(3 yrs)</strong></th>");
                strEmailBody.Append("<th width='45%' align='center' style=\"background:#c5c5c5;\"><strong>Lock-In</strong></th>");
                for (int p = 0; p < arrSelectedPackage.Length; p++)
                {
                    if (arrSelectedPackage[p] != "")
                    {
                        strEmailBody.Append(arrSelectedPackage[p]);
                    }
                }
                strEmailBody.Append("</table>");
                strEmailBody.Append("<hr size='1' color='#b8b8b8' width='510'/>");
                strEmailBody.Append("</td></tr>");
                strEmailBody.Append("<tr><td><a href=\"http://www.comparexpress.com/\" target=\"_blank\"><img src=\"" + _baseUrl + "/images/email/footer_quote.png\" alt='CompareXpress - Partners' width=\"596\" height=\"174\" border=\"0\" /></a></td></tr>");
                strEmailBody.Append("</table></center>");
                strEmailBody.Append("</body>");
                Session[General.HLEmail] = txtEmail.Text;
                Session[General.HLPhoneNo] = txtMobileNo.GetPhoneNo();
                Session[General.HLUserName] = txtFullName.Text;
                if (SendEmailToUser(txtEmail.Text, "CompareXpress - Home Loans Selected Packages " + CE.Global.General.GetUTCDateTime().ToString(), strEmailBody.ToString()))
                {
                    Response.Redirect("usermessage.aspx");
                }
                else
                {
                    divPopUpMessage.Visible = true;
                    lblPopUpMessage.Text = "Email failed to send.<br/>Please try again later.";
                }
            }
            else
            {
                Response.Redirect("home-loan.aspx");
            }
        }
    }

    private bool SendEmailToUser(string emailTo, string emailSubject, string mailBody)
    {
        bool _retVal = false;

        string _currentDomainUrl = "http://" + HttpContext.Current.Request.Url.Host.ToString();
        string imgLogoUrl = _currentDomainUrl + CE.Configuration.MyConfigurationManager.GetAppSettingValue("LogoPath");
        //mailBody += "<br/><br />Yours,<br/><a href='http://www.comparexpress.com' target='_blank'><img src='" + imgLogoUrl + "' alt='CompareXpress Team' /></a><br/><br/><i>This is a computer-generated email. Please do not reply to this email.</i>";
        //emailTo += ";comparexpressteam@gmail.com;";
        string hl_emailTo = CE.Configuration.MyConfigurationManager.GetAppSettingValue("HL_TOEmail");
        string hl_emailCC = CE.Configuration.MyConfigurationManager.GetAppSettingValue("HL_CCEmail");
        string hl_emailBCC = CE.Configuration.MyConfigurationManager.GetAppSettingValue("HL_BCCEmail");
        emailTo += ";" + hl_emailTo;
        if (MyMailManager.SendCRMMessage(emailTo, hl_emailCC, hl_emailBCC, emailSubject, mailBody))
        {
            _retVal = true;
        }

        return _retVal;
    }

    protected void imgbtnCompare_Click(object sender, ImageClickEventArgs e)
    {
        //string sQueryString = "";
        //bool isChecked;
        //foreach (GridViewRow vRow in gvHLResults.Rows)
        //{
        //    isChecked = ((CheckBox)vRow.FindControl("cbHLSelect")).Checked;
        //    if (isChecked)
        //    {
        //        string skey = ((Label)vRow.FindControl("lblTempId")).Text;
        //        sQueryString += skey + ",";
        //    }
        //}

        //Session["HLSelected"] = sQueryString;

        //Response.Redirect("results-details.aspx");
    }
}
